﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using Irony.Ast;
using Irony.Interpreter;
using Irony.Parsing;
using ConciseMarkupLanguage.Utils;

namespace ConciseMarkupLanguage.Ast
{
    class TagBlockNode : AstNode
    {
        private AstNode _attrNode = null;
        private AstNode _contentNode = null;
        private string _tagStr = "";

        public override void Init(ParsingContext context,ParseTreeNode treeNode)
        {
            base.Init(context, treeNode);
            AsString = _tagStr = treeNode.ChildNodes[0].FindTokenAndGetText();

            if (treeNode.ChildNodes.Count > 1)
            {
                if (treeNode.ChildNodes[1].AstNode is AttrListNode)
                {
                    _attrNode = AddChild("attributes", treeNode.ChildNodes[1]);
                    if (treeNode.ChildNodes.Count > 2) _contentNode = AddChild("content", treeNode.ChildNodes[2]);
                }
                else _contentNode = AddChild("content", treeNode.ChildNodes[1]);
            }
        }

        public override void EvaluateNode(EvaluationContext context, AstMode mode)
        {
            string content = null;
            AttrDict attrs = null;
            var sb = new StringBuilder();

            if (_attrNode != null)
            {
                _attrNode.Evaluate(context, AstMode.Read);
                attrs = (AttrDict)context.Data.Pop();
            }

            while (context.Data.Count > 0)
                sb.Append(context.Data.Pop());

            if (_contentNode != null)
            {
                _contentNode.Evaluate(context, AstMode.Read);
                while (context.Data.Count > 0)
                    context.OutputBuffer.Append(context.Data.Pop());
                content = context.OutputBuffer.ToString();
                context.OutputBuffer.Clear();
            }

            context.OutputBuffer.Append(sb);
            context.OutputBuffer.Append(CmlGrammar.TemplateTags[_tagStr].Invoke(null, new object[] { attrs, content }));
        }
    }
}
